package com.tianyi.sysUser;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.tianyi.dao.entity.role.Role;
import com.tianyi.dao.entity.sysUser.SysUser;
import com.tianyi.dao.entity.sysUser.SysUserExample;
import com.tianyi.dao.mapper.RoleMapper;
import com.tianyi.dao.mapper.SysUserMapper;
import com.tianyi.lib.bo.PullDownBO;
import com.tianyi.lib.enums.SysUserStatus;
import com.tianyi.lib.enums.SysUserTypes;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.SysUserReq;
import com.tianyi.model.SimpleLoginUser;
import com.tianyi.role.RoleService;
import com.tianyi.util.EncryptUtil;
import com.tianyi.vo.PullDownVO;
import com.tianyi.vo.sysUser.SysUserVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统用户service
 *
 * @author cuixuhui
 */
@Service
public class SysUserService {

    private static final Logger logger = LoggerFactory.getLogger(SysUserService.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleMapper roleMapper;

    private WebResult<String> preCheck(SysUserReq req){

        if (StringUtils.isBlank(req.getUserName())){
            return WebResult.error("登陆名不能为空");
        }
        if (StringUtils.isBlank(req.getUserNameCn())){
            return WebResult.error("真实姓名不能为空");
        }
        if (StringUtils.isBlank(req.getPassword())){
            req.setPassword("123456");
        }
        if (Objects.isNull(req.getPhone())){
            return WebResult.error("手机号码不能为空");
        }
        if (Objects.isNull(req.getEntryTime())){
            req.setEntryTime(new Date());
        }
        if (Objects.isNull(req.getUserType())){
            req.setUserType(SysUserTypes.COMMON);
        }
        if (Objects.isNull(req.getUserStatus())){
            req.setUserStatus(SysUserStatus.enable);
        }
        if (Objects.isNull(req.getRoleId())){
            return WebResult.error("权限不能为空");
        }

        Role role = roleService.queryRoleByRoleId(req.getRoleId());
        if (Objects.isNull(role)){
            return WebResult.error("权限不存在");
        }

        //邮箱不验证

        return WebResult.ok("ok");
    }

    public SysUser generateByReq(SysUser sysUser, SysUserReq req){

        if (Objects.isNull(sysUser)) {
            sysUser = new SysUser();
            sysUser.setGmtCreate(new Date());
        }
        sysUser.setGmtModified(new Date());

        sysUser.setPhone(req.getPhone());

        String pwdEncrypt = EncryptUtil.pwdEncrypt(req.getPassword());
        sysUser.setPwd(pwdEncrypt);

        sysUser.setUserName(req.getUserName());
        sysUser.setUserNameCn(req.getUserNameCn());
        sysUser.setUserType(roleMapper.selectByPrimaryKey(req.getRoleId()).getRoleCode());
        sysUser.setEntryTime(req.getEntryTime());
        sysUser.setMail(req.getMail());
        sysUser.setRemark(req.getRemark());
        sysUser.setOperator(req.getEmpId());
        sysUser.setStatus(req.getUserStatus().name());

        sysUser.setRoleId(req.getRoleId());
        return sysUser;
    }

    public WebResult<String> addSysUser(SysUserReq req){

        WebResult<String> preCheck = preCheck(req);
        if (!preCheck.isSuccess()){
            return preCheck;
        }
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(req.getUserName());
        example.or().andPhoneEqualTo(req.getPhone());

        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(sysUsers)){
            return WebResult.error("用户已存在,请检查登陆名/手机号");
        }

        SysUser sysUser = generateByReq(null, req);
        int insert = sysUserMapper.insert(sysUser);

        return WebResult.ok("success");
    }

    public WebResult<String> updateSysUser(SysUserReq req) {

        Long empId = req.getId();
        if (Objects.isNull(empId)){
            return WebResult.error("用户id为空");
        }
        WebResult<String> preCheck = preCheck(req);
        if (!preCheck.isSuccess()){
            return preCheck;
        }
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(empId);
        if (Objects.isNull(sysUser)){
            return WebResult.error("用户不存在");
        }
        sysUser = generateByReq(sysUser, req);
        int insert = sysUserMapper.updateByPrimaryKey(sysUser);
        return WebResult.ok("success");
    }

    public WebResult<String> deleteSysUser(SysUserReq req) {
        int delete = sysUserMapper.deleteByPrimaryKey(req.getId());
        return WebResult.ok("success");
    }

    public WebResult<PageInfo<SysUserVO>> querySysUserPage(SysUserReq req){

        SysUserExample example = new SysUserExample();
        example.setOrderByClause("id DESC");
        SysUserExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(req.getUserName())){
            criteria.andUserNameEqualTo(req.getUserName());
        }
        if (Objects.nonNull(req.getPhone())){
            criteria.andPhoneEqualTo(req.getPhone());
        }
        Page<SysUser> sysUsers = sysUserMapper.selectByExample(example, new RowBounds(req.getPageNo(), req.getPageSize()));
        PageInfo<SysUser> sysUserPageInfo = sysUsers.toPageInfo();

        PageInfo<SysUserVO> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(sysUserPageInfo, pageInfo);

        List<SysUser> userPageInfoList = sysUserPageInfo.getList();
        if (CollectionUtils.isEmpty(userPageInfoList)){
            return WebResult.ok(pageInfo);
        }

        WebResult<List<PullDownVO>> rolePullDown = roleService.getRolePullDown();
        List<PullDownVO> pullDownData = rolePullDown.getData();
        Map<Long, String> roleIdRoleNameMap = ListUtils.emptyIfNull(pullDownData).stream().collect(Collectors
                .toMap(ret -> Long.valueOf(ret.getValue().toString()), ret -> ret.getLabel().toString(), (oldOne, newOne) -> newOne));

        List<SysUserVO> userVOList = userPageInfoList.stream().map(ret -> {
//            String pwd = ret.getPwd();
//            String s = EncryptUtil.pwdDecrypt(pwd);
            ret.setPwd(null);

            SysUserVO vo = new SysUserVO();
            BeanUtils.copyProperties(ret, vo);
            String roleName = roleIdRoleNameMap.get(vo.getRoleId());
            String realRoleName = StringUtils.isBlank(roleName) ? "权限已删除" : roleName;
            vo.setRoleName(realRoleName);
            return vo;
        }).collect(Collectors.toList());
        pageInfo.setList(userVOList);
        return WebResult.ok(pageInfo);
    }

    public SysUser queryUserByEmpId(Long empId){
        if (empId == null){
            return null;
        }
        return sysUserMapper.selectByPrimaryKey(empId);
    }

    public WebResult<List<PullDownBO>> getUserType() {

        List<SysUserTypes> userTypes = Arrays.asList(SysUserTypes.values());

        List<PullDownBO> pmsType = userTypes.stream().map(ret -> {
            PullDownBO bo = new PullDownBO();
            bo.setLabel(ret.getValue());
            bo.setValue(ret.name());
            return bo;
        }).collect(Collectors.toList());
        return WebResult.ok(pmsType);
    }

    /**
     * 登陆方法
     * @param loginParam
     * @param pwd
     * @return
     */
    public WebResult<SimpleLoginUser> login(String loginParam, String pwd) {

        if (StringUtils.isBlank(loginParam)){
            return WebResult.error("登陆名不能为空");
        }
        if (StringUtils.isBlank(pwd)){
            return WebResult.error("密码不能为空");
        }
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(loginParam)){
            criteria.andUserNameEqualTo(loginParam);
            try {
                Long phone = Long.valueOf(loginParam);
                example.or().andPhoneEqualTo(phone);
            }catch (Exception e){
                logger.info("loginParam valueOf2long fail");
            }
        }

        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(sysUsers)){
            return WebResult.error("用户不存在");
        }
        String pwdEncrypt = EncryptUtil.pwdEncrypt(pwd);
        List<SysUser> loginUser = sysUsers.stream().filter(ret -> StringUtils.equals(ret.getPwd(), pwdEncrypt)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(loginUser)){
            return WebResult.error("用户密码不正确");
        }
        //这种概率极小,不过还是等出现了再处理
        if (loginUser.size() > 1){
            return WebResult.error("用户存在脏数据,请联系管理员");
        }
        SimpleLoginUser user = new SimpleLoginUser();
        SysUser sysUser = loginUser.get(0);
        user.setEmpId(sysUser.getId());
        user.setUserName(sysUser.getUserName());
        if (StringUtils.isNotBlank(sysUser.getUserType())){
            user.setUserType(SysUserTypes.valueOf(sysUser.getUserType()));
        }
        user.setRoleId(sysUser.getRoleId());
        user.setPhone(sysUser.getPhone());

        return WebResult.ok(user);
    }

    /**
     * 获取系统用户翻译
     * @param ids
     * @return
     */
    public Map<Long, String> queryUserNameMapByUserIds(List<Long> ids){

        if (CollectionUtils.isEmpty(ids)){
            return Maps.newHashMap();
        }

        SysUserExample example = new SysUserExample();
        example.setOrderByClause("id DESC");
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(ids);
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        Map<Long, String> idUserNameMap = ListUtils.emptyIfNull(sysUsers).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getUserName, (oldOne, newOne) -> newOne));
        return idUserNameMap;
    }
}
